package com.anxin.registerManagement.filter;

import cn.hutool.core.util.ObjectUtil;
import com.anxin.registerManagement.exception.AuthException;
import com.anxin.registerManagement.exception.BusinessException;
import com.anxin.registerManagement.util.Const;
import com.anxin.registerManagement.util.ResultUtil;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

/**
 * @author 叶前呈
 * @date 2022/1/20 23:05
 */
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public ResultUtil globalExceptionHandler(Exception ex) {
        String message = "";
        LOGGER.error(ex.getMessage());
        if (ex instanceof BusinessException) { // 业务异常处理
            return ResultUtil.fail(ex.getMessage());
        } else if (ex instanceof UnknownAccountException) { //用户名不存在异常
            return ResultUtil.fail(Const.UNKNOW_USERNAME);
        } else if (ex instanceof IncorrectCredentialsException) { //密码不正确异常
            return ResultUtil.fail(Const.UNKNOW_PASSWORD);
        } else if (ex instanceof UnauthorizedException) { //无权限访问
            return ResultUtil.fail(401, Const.UN_AUTHORIZED);
        } else if (ex instanceof AuthorizationException) {
            return ResultUtil.fail(401, Const.REQUIRE_LOGIN);
        } else if (ex instanceof AuthException) { // 统一权限异常返回
            return ResultUtil.fail(40000, ex.getMessage());
        } else if (ex instanceof ConstraintViolationException) { // url参数校验失败
            message = ex.getMessage();
            return ResultUtil.fail(message);
        } else if (ex instanceof MethodArgumentNotValidException) { // Bean属性校验失败
            MethodArgumentNotValidException mavEx = (MethodArgumentNotValidException) ex;
            FieldError fieldError = (FieldError) mavEx.getBindingResult().getAllErrors().get(0);
            message = fieldError.getDefaultMessage();
            return ResultUtil.fail(message);
        }
        return ResultUtil.fail(40000, ex.getMessage(), ex);
    }
}
